package whf.framework.util;

import java.util.UUID;

import whf.framework.meta.Meta;
import whf.framework.security.UserContext;
import whf.framework.security.entity.User;
import whf.framework.web.WebContextHolder;

/**
 * @author wanghaifeng
 * @create Aug 25, 2006 10:16:43 PM
 * 
 */
public final class ThreadContext {
	// 线程用户上下文
	private static ThreadLocal<UserContext> userContextThreadLocal = new ThreadLocal<UserContext>();
	
	public static void setUserContext(UserContext uc){
		userContextThreadLocal.set(uc);
	}
	
	public static UserContext getUserContext(){
		WebContextHolder wc = WebContextHolder.getWebContext();
		if(wc != null) return wc.getUserContext();
		return userContextThreadLocal.get();
	}
	
	public static User getUserInUserContext() {
		UserContext uc = getUserContext();
		if(uc != null) 
			return uc.getUser();
		else
			return null;
	}
	
	public static String getSessionId(){
		UserContext uc = getUserContext();
		if(uc == null){
			return UUID.randomUUID().toString();
		} else {
			return uc.getSessionId();
		}
	}
	
	// 
	private static ThreadLocal<String> dataSourceNameThreadLocal = new ThreadLocal<String>();
	
	public static void setCurrentDataSourceName(String dataSourceName) {
		dataSourceNameThreadLocal.set(dataSourceName);
	}
	
	public static String getCurrentDataSourceName() {
		return dataSourceNameThreadLocal.get();
	}
	
	/**
	 * 线程日志开关,缺省true为开,关闭日志,主动设计为false
	 */
	private static ThreadLocal<Boolean> auditSwitch = new ThreadLocal<Boolean>();
	
	public static void setAuditableInThread(boolean value) {
		auditSwitch.set(value);
	}
	
	public static boolean isAuditableInThread() {
		if(auditSwitch.get() != null && !auditSwitch.get().booleanValue())
			return false;
		else
			return true;
	}
	
	// 当前操作对象
	private static ThreadLocal<Meta> metaThreadLocal = new ThreadLocal<Meta>();
	
	public static void setCurrentMeta(Meta meta) {
		metaThreadLocal.set(meta);
	}
	
	public static Meta getCurrentMeta() {
		return metaThreadLocal.get();
	}
}
